package com.lfs.utils;


import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import java.io.*;

public class FileUtil {

    /**
     * 根据文件路径获取文件数据
     * @return 下载文件
     */
    public File getTemplateFromServer(String host, String user, String password, String remoteFilePath) {
        Session session = null;
        ChannelSftp channelSftp = null;
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(user, host, 22);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            channelSftp = (ChannelSftp) session.openChannel("sftp");
            channelSftp.connect();

            // 创建临时文件
            File tempFile = File.createTempFile("template", ".xlsx");
            tempFile.deleteOnExit();

            // 下载文件到临时文件
            FileOutputStream fos = new FileOutputStream(tempFile);
            InputStream is = channelSftp.get(remoteFilePath);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }
            fos.close();
            is.close();

            return tempFile;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("从服务器下载模板文件时出错", e);
        } finally {
            if (channelSftp != null && channelSftp.isConnected()) {
                channelSftp.disconnect();
            }
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
    }
}
